<template>
    <div class="edu-header">
        <div class="edu-header-left">
            <div class="float-left">
                <div
                    v-if="!showMenu"
                    ref="showTopMenuBtn"
                    class="show-menus-btn close"
                    @click="showMenu = !showMenu"
                />
                <div
                    v-else
                    ref="showTopMenuBtn"
                    class="show-menus-btn open"
                    @click="showMenu = !showMenu"
                />
            </div>
            <div class="edu-header-logo"></div>
        </div>
        <div v-if="!isPort" class="edu-header-right">
            <!-- 新版首页隐藏消息列表 -->
            <!-- <div class="edu-item">
                <msg-list></msg-list>
            </div> -->
            <div class="edu-item">
                <user-select
                    @updateCurrentManageDptId="handlerupdateCurrentManageDptId"
                    :mock-user="mockUser"
                    :show-switch="showSwitch"
                />
            </div>
            <!-- 语言切换 -->
            <div class="edu-item">
                <lang-select />
            </div>
            <!-- 用户信息展示、退出 -->
            <div class="edu-item">
                <system-select @avartarClick="showRuleSelectDialog" />
            </div>
            <!-- 用户身份切换 -->
            <div  v-if="!!identity.name && !isMockingStudent && isAll" class="edu-item">
                <el-dropdown trigger="click" @command="handlerChangeIdentity">
                        <span class="el-dropdown-link">{{identity.name}}
                            <i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item
                            v-for="(item, index) in identityOpts"
                            :key="index"
                            :command="item"
                        >{{item.name}}</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
            <div class="edu-item" v-if="!isMockingStudent && !isAll">
                        <span>{{onlyIdentity.name}}</span>
            </div>
            <!-- 管理部门切换 -->
            <div class="edu-item">
                <department-select
                    v-if="isShowDepartment"
                    @updateCurrentManageDptId="handlerupdateCurrentManageDptId"
                />
            </div>
        </div>
        <div v-if="showMenu" class="edu-menus-box">
            <TopMenu :show-menu="showMenu" :menus="menus" @change-visiable="changeVisiable" />
        </div>
    </div>
</template>
<script>
import LangSelect from 'common/src/components/LangSelect'
import SystemSelect from 'common/src/components/SystemSelect'
import MsgList from 'common/src/components/MsgList'
import TopMenu from 'common/src/components/TopMenu'
import UserSelect from 'common/src/components/UserSelect'
import DepartmentSelect from 'common/src/components/DepartmentSelect'
import Bus from 'common/src/utils/bus'
import { toggleCurrentUserRole } from 'common/src/api/session'
import mixin from 'common/src/mixins/index'
import { getSessionUser } from 'common/src/api/session'

export default {
    name: 'Navbar',
    inject: ['reload'],
    mixins: [mixin],
    props: {
        isLogin: Boolean,
        userName: String,
        isPort: Boolean,
        menus: {
            type: Object,
            default: function() {
                return {
                    activeMenu: '',
                    activeSubMenu: '',
                    menuItems: []
                }
            }
        },
        auths: Array,
        mockUser: Object,
        showSwitch: Boolean
    },
    components: {
        LangSelect,
        SystemSelect,
        MsgList,
        TopMenu,
        UserSelect,
        DepartmentSelect
    },
    data() {
        return {
            showMenu: false,
            isShowDepartment: false,
            showRuleSelect: false,
            identity: {
                name: '',
                id: ''
            },
            onlyIdentity: {
                name: '',
                id: ''
            },
            identityOpts: [
                {
                    name: this.$t('identity.manager'),
                    id: '1'
                },
                {
                    name: this.$t('identity.teacher'),
                    id: '2'
                }
            ],
            isAll:null
        }
    },
    mounted() {
        this.setUserAuth()
    },
    methods: {
        /**
         * 菜单恢复到初始化workbench
         */
        tabInit(){
            Bus.$emit('updateCurrentRole')
        },
        changeVisiable(target) {
          if (this.showMenu && this.$refs.showTopMenuBtn != target) this.showMenu = false
        },
        showRuleSelectDialog() {
            // 兼容切换用户功能，切换用户后，是否显示角色切换，取当前用户数据（mockuser or user）
            let innerRoles = (this.global.mockUser ? this.global.mockUser : this.global.user)
                .innerRoles
            if (innerRoles instanceof Array && innerRoles.length > 0) {
                if (
                    (innerRoles.indexOf('1') > -1 || innerRoles.indexOf('2') > -1) &&
                    (innerRoles.indexOf('3') > -1 || innerRoles.indexOf('4') > -1)
                ) {
                    this.showRuleSelect = true
                }
            }
        },
        handlerupdateCurrentManageDptId(id) {
            this.currentUser.currentManageDptId = id
            this.setUserAuth()
            this.tabInit()
        },
        setUserAuth() {
            let userRole = this.currentUser.currentRole
            let userType = this.currentUser.type
            // 身份判定
            this.identity = this.identityOpts.find(item => item.id === userRole) || {}
            let innerRoles = this.currentUser.innerRoles
            let hasShowRuleSelectAuth =
                innerRoles && innerRoles instanceof Array && innerRoles.length > 0
                    ? (innerRoles.indexOf('1') > -1 || innerRoles.indexOf('2') > -1) &&
                      (innerRoles.indexOf('3') > -1 || innerRoles.indexOf('4') > -1)
                    : false
            this.showRuleSelect =
                hasShowRuleSelectAuth &&
                (!userRole || userRole == '0') &&
                userType != '2' &&
                this.flag != 1
            // let { manageDptIds, currentManageDptId } = this.currentUser

            // console.log('asdfasdf');
            // console.log(currentManageDptId ||
            //     (manageDptIds && manageDptIds instanceof Array && manageDptIds.length > 0
            //         ? manageDptIds[0]
            //         : ''));
            // this.currentUser.currentManageDptId =
            //     currentManageDptId ||
            //     (manageDptIds && manageDptIds instanceof Array && manageDptIds.length > 0
            //         ? manageDptIds[0]
            //         : '')

            this.isShowDepartment =
                this.global.currentUser.currentRole == '1' &&
                this.global.currentUser.currentManageDptId !== '' &&
                this.global.currentUser.type !== '2'
            if(!this.isShowDepartment) {
                this.identity = this.identityOpts[1]
            }
            this.handelChangeIdentityBtn();
            // this.setLocalUser(this.currentUser)
        },
        handelChangeIdentityBtn() {
            let innerRoles = this.global.currentUser.innerRoles, manageList = [];
            if (innerRoles.indexOf('1') > -1 || innerRoles.indexOf('2') > -1) {
                manageList.push(1);
                this.onlyIdentity = this.identityOpts[0]
            }
            if (innerRoles.indexOf('3') > -1 || innerRoles.indexOf('4') > -1) {
                manageList.push(1);
                this.onlyIdentity = this.identityOpts[1]
            }
            if (manageList.length == 1) {
                this.isAll = false;
            } else {
                this.isAll = true;
            }
        },
        // setLocalUser(newValue) {
        //     // this.$store.state.session.user = newValue
        //     localStorage.setItem('user', JSON.stringify(newValue))
        //     let sessionData = JSON.parse(localStorage.getItem('sessiondata'))
        //     if (sessionData) {
        //         sessionData.user = newValue
        //         localStorage.setItem('sessiondata', JSON.stringify(sessionData))
        //     }
        // },
        initLocalTabs() {
            let tabs = this.$store.state.common.tabs.slice(0);
            localStorage.setItem("tabs", JSON.stringify(tabs));
        },
        handlerChangeIdentity(item) {
            if (item.id === this.identity.id) {
                return
            }
            this.identity = item
            toggleCurrentUserRole({ currentRole: this.identity.id }).then(
                res => {
                    if (res.code === 200) {
                        let identityId = this.identity.id
                        this.$store.commit('set_session_data', res.data)
                        this.currentUser.currentRole = identityId
                        this.setUserAuth()
                        this.tabInit()
                        Bus.$emit('updateCurrentRole', identityId)
                        this.initLocalTabs()
                        this.reload()
                    } else {
                        this.$message({
                            type: 'error',
                            message: this.$t('identity.failSelectRule')
                        })
                    }
                },
                () => {
                    this.$message({
                        type: 'error',
                        message: this.$t('identity.failSelectRule')
                    })
                }
            )
        }
    },
    computed: {
        currentUser() {
            if (this.$store.state.session.user) {
                return this.$store.state.session.user
            }
            return JSON.parse(localStorage.getItem('user'))
        },
        isMockingStudent() {
            // const mockUser = JSON.parse(localStorage.getItem("sessiondata")).mockUser;
            let session = this.$store.state.session
            let user = session.mockUser ? session.mockUser : session.user
            return  user && user.type == 2
        }
    },
    watch: {
        $route(to) {
            this.showMenu = false
        }
    }
}
</script>
<style lang="scss" scoped>
.edu-header {
    position: relative;
    width: 100%;
    height: 64px;
    padding: 0 16px;
    background-color: #fff;
    ::v-deep{
        .el-icon--right{
           margin-left:0 !important
        }
    }
    .edu-header-left {
        float: left;
        padding: 12px 0;
        .edu-header-logo {
            float: left;
            width: 380px;
            height: 40px;
            background: url('/static/images/icon_logo.png');
        }
    }
    .edu-header-right {
        float: right;
        display: flex;
        align-items: center;
        height: 100%;
        .edu-item {
            margin-left: 10px;
        }
    }
    .edu-menus-box {
        position: absolute;
        width: 100%;
        left: 0;
        top: 64px;
        z-index: 2009;
        box-shadow: 0px 2px 5px 2px rgba(226, 228, 230, 0.97);
        background: #fff;
    }
    .show-menus-btn {
        display: inline-block;
        margin: 12px 24px 0 0;
        width: 20px;
        height: 20px;
        cursor: pointer;
        transition: all 0.32s ease-in-out;
        background: url('/static/images/menu-open.png');
        &.close {
            transform: rotate(-90deg);
        }
        &.open {
            transform: rotate(0);
        }
    }
    .el-dropdown-link {
    cursor: pointer;
    color: #3A7FE8;
  }
}
</style>
